import wsgiref.util
import cgi
import urlparse
import datetime
import time

import MSConfig; MSConfig.init('.')
import MSLogger2; log = MSLogger2.get('wsgi_server')
import MSWSGIPatterns as w
import MSDatetime
import MSDatabase

def get_monitor_menu():
    ret = [
        '<ul class="tabs">'\
        '  <li class="active"><a href="#">Home</a></li>'\
        '  <li><a href="#">Profile</a></li>'\
        '  <li><a href="#">Messages</a></li>'\
        '  <li><a href="#">Settings</a></li>'\
        '  <li><a href="#">Contact</a></li>'\
        '</ul>']
    return ret


def method_msysreceiver_start(environ):
    ret = []
    try:
        if MSDatabase.instance == None:
            db = MSDatabase.Database(MSConfig.config.get('main','dbpath'))
            MSDatabase.instance = db
            db.start()
            #db.setAutoSync('msdb', 20)
            log.info('method_msysreceiver_start: done')
            ret += ['started']
        else:
            ret += ['already started']
    except Exception, err:
        log.error('method_msysreceiver_start: failed %s', str(err))
        ret += ['failed to start: %s' % (str(err))]
    return ret

def method_msysreceiver_stop(environ):
    ret = []
    try:
        MSDatabase.getInstance().stop()
        MSDatabase.instance = None
        ret += ['stopped']
    except Exception, err:
        log.error('method_msysreceiver_stop: failed %s', str(err))
        ret += ['already stopped']
    return ret

def method_msysreceiver_configure(environ):
    form    = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
    ms_host = form.getvalue('ms_host')
    ms_port = form.getvalue('ms_port')
    ms_dbname   = form.getvalue('ms_dbname')
    ms_comport  = form.getvalue('ms_comport')

    MSConfig.config.set('msdb', 'host', ms_host)
    MSConfig.config.set('msdb', 'port', ms_port)
    MSConfig.config.set('msdb', 'dbname', ms_dbname)
    MSConfig.config.set('mswriter', 'port', ms_comport)
    MSConfig.write('.')
    return ['configuration saved']

def method_msysreceiver_com(environ):
    ret = []
    ret += ['\
        <form action="/method/msysreceiver_com_configure" method="post"> \
        <fieldset> \
        <legend>MSys COM Port Configure</legend> \
            <div class="clearfix"> \
                <label for="ms_bodrate">Bod Rate</label> \
                <div class="input"> \
                    <input class="span8" id="ms_bodrate" name="ms_bodrate" size="30" type="text" value=""> \
                </div>\
            </div>\
            <div class="clearfix">\
                <label for="ms_bitdata">Bit Data</label>\
                <div class="input">\
                    <input class="span8" id="ms_bitdata" name="ms_bitdata" size="30" type="text" value="">\
                </div>\
            </div>\
            <div class="clearfix">\
                <label for="ms_stopbit">Stop Bit</label>\
                <div class="input">\
                    <input class="span8" id="ms_stopbit" name="ms_stopbit" size="30" type="text" value="">\
                </div>\
            </div>\
            <div class="clearfix">\
                <label for="ms_parity">Parity</label>\
                <div class="input">\
                    <input class="span8" id="ms_parity" name="ms_parity" size="30" type="text" value="">\
                </div>\
            </div>\
            <div class="clearfix">\
                <label for="ms_flowcontrol">Flow Control</label>\
                <div class="input">\
                    <input class="span8" id="ms_flowcontrol" name="ms_flowcontrol" size="30" type="text" value="">\
                </div>\
            </div>\
        </fieldset>\
        <button class="btn primary" type="submit">Save</button>\
        </form>\
           ']
    return ret


def method_msysreceiver(environ):
    ret = []
    labeltype = 'important'
    labeltext = 'stopped'
    if MSDatabase.instance != None:
        labeltype = 'success'
        labeltext = 'started'
    ret += ['<div class="row">'\
            '<div class="span2"><span class="label %s">%s</span></div>'\
            '</div>' % (labeltype, labeltext)]
    ret += ['<div class="span12">']
    ret += ['\
        <form action="/method/msysreceiver_configure" method="post"> \
        <fieldset> \
        <legend>MSys Settings</legend> \
            <div class="clearfix"> \
                <label for="ms_host">Host</label> \
                <div class="input"> \
                    <input class="span8" id="ms_host" name="ms_host" size="30" type="text" value="%s"> \
                </div>\
            </div>\
            <div class="clearfix">\
                <label for="ms_port">Port</label>\
                <div class="input">\
                    <input class="span8" id="ms_port" name="ms_port" size="30" type="text" value="%s">\
                </div>\
            </div>\
            <div class="clearfix">\
                <label for="ms_dbname">Database Name</label>\
                <div class="input">\
                    <input class="span8" id="ms_dbname" name="ms_dbname" size="30" type="text" value="%s">\
                </div>\
            </div>\
            <div class="clearfix">\
                <label for="ms_comport">COM Port Number</label>\
                <div class="input">\
                    <input class="span8" id="ms_comport" name="ms_comport" size="30" type="text" value="%s">\
                </div>\
                <a href="/method/msysreceiver_com">COM Port Settings</a>\
            </div>\
        </fieldset>\
        <button class="btn primary" type="submit">Save</button>\
        </form>\
           ' % (MSConfig.config.get('msdb', 'host'),
                MSConfig.config.get('msdb', 'port'),
                MSConfig.config.get('msdb', 'dbname'),
                MSConfig.config.get('mswriter', 'port'))]
    ret += ['</div>']
    ret += ['<div class="span12">']
    if MSDatabase.instance == None:
        ret += ['\
            <form action="/method/msysreceiver_start" method="post"> \
            <fieldset> \
            <button class"btn success" type="submit">Start MSys receiver</button>\
            </fieldset> \
            </form>\
                ']
    else:
        ret += ['\
            <form action="/method/msysreceiver_stop" method="post"> \
            <button class"btn danger" type="submit">Stop MSys receiver</button>\
            </form>\
                ']
    ret += ['</div>']
    return ret

def method_naviguardreceiver(environ):
    ret = ['not implemented yet']
    return ret
def method_eldosreceiver(environ):
    ret = ['not implemented yet']
    return ret

def method_get_logs(environ):
    f = open('wsgi_server.log', 'r')
    r = []
    d = f.readlines()
    for s in d:
        r += [s + '<br>']
    return r

def method_get_monitor(environ):
    ret = []
    labeltype = 'important'
    labeltext = 'MSys receiver stopped'
    if MSDatabase.instance != None:
        labeltype = 'success'
        labeltext = 'MSys receiver started'
    ret += ['<div class="row">'\
            '<div class="span4">status</div>'
            '<div class="span4"><span class="label %s">%s</span></div>'\
            '<div class="span4"><span class="label important">Naviguard receiver stopped</span></div>'\
            '<div class="span4"><span class="label important">Eldos receiver stopped</span></div>'\
            '</div>' % (labeltype, labeltext)]
    ret += ['<div class="row">'\
            '<div class="span4">devices total</div>'
            '<div class="span4"><span class="label default">11</span></div>'\
            '<div class="span4"><span class="label default">5</span></div>'\
            '<div class="span4"><span class="label default">0</span></div>'\
            '</div>']
    ret += ['<div class="row">'\
            '<div class="span4">devices online</div>'
            '<div class="span4"><span class="label success">10</span></div>'\
            '<div class="span4"><span class="label success">3</span></div>'\
            '<div class="span4"><span class="label success">0</span></div>'\
            '</div>']
    ret += [
            '<h3>System events</h3><br/><table class="zebra-striped" id="eventTableSortable" ><thead><tr><th class="header" >time</th><th class="yellow header" >message</th><th class="yellow header" >id</th><th class="blue header" >pgsm type</th><th class="green header" >cid</th></tr></thead><tbody class="eventTableBody" id="eventTableBody"><tr><th>2011-10-18 22:25:32</th><th>Event of Unknown Contact ID Type 000</th><th>24802</th><th>98</th><th>1800141000000990</th></tr><tr><th>2011-10-18 22:25:30</th><th>Event of Unknown Contact ID Type 000</th><th>24803</th><th>41</th><th>1800141000000990</th></tr><tr><th>2011-10-18 22:24:32</th><th>Event of Unknown Contact ID Type 000</th><th>24800</th><th>98</th><th>1800141000000990</th></tr><tr><th>2011-10-18 22:24:29</th><th>Event of Unknown Contact ID Type 000</th><th>24801</th><th>41</th><th>1800141000000990</th></tr><tr><th>2011-10-18 22:23:33</th><th>Event of Unknown Contact ID Type 000</th><th>24798</th><th>98</th><th>1800141000000990</th></tr><tr><th>2011-10-18 22:23:30</th><th>Event of Unknown Contact ID Type 000</th><th>24799</th><th>41</th><th>1800141000000990</th></tr><tr><th>2011-10-18 22:22:33</th><th>Event of Unknown Contact ID Type 000</th><th>24796</th><th>98</th><th>1800141000000990</th></tr><tr><th>2011-10-18 22:22:29</th><th>Event of Unknown Contact ID Type 000</th><th>24797</th><th>41</th><th>1800141000000990</th></tr><tr><th>2011-10-18 22:21:32</th><th>Event of Unknown Contact ID Type 000</th><th>24795</th><th>98</th><th>1800141000000990</th></tr></tbody></table>'
           ]
    #ret += get_monitor_menu()
    return ret

'''
def method_eldosreceiver(environ):
    form    = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)

    if form.getvalue('obj_fromDisk'):
        fromDisk = True
    else:
        fromDisk = False

    name = form.getvalue('obj_name')
    if not w.checkName(name): 
        if not name: name = ''
        log.debug('method_get_object_events: incorrect name %s', name)
        return ['object ' + name + ' not found']
    if fromDisk:
        obj = MSObject.MSObject(MSConfig.config.get('main', 'dbpath'), name)
        obj.open()
    else:
        obj = MSDatabase.getInstance().objs.find(name)
    if (not obj) or  obj.storage.txn == 0:
        log.debug('method_get_object: not found %s', name)
        return ['object ' + name + ' not found']

    ret = []
    ret += w.openObjectCommonTable()
    ret += w.getObjectCommonInfo(1, obj)
    ret += w.closeObjectCommonTable()

    ret += w.getObjectDetailedInfo(obj)

    return ret

def method_destroy_object(environ):
    form    = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
    obj_name = form.getvalue('obj_name')

    obj     = MSObject.MSObject(MSConfig.config.get('main','dbpath'), obj_name)
    obj.open()
    if obj.storage.txn == 0:
        return ['object does not exist']
    obj.storage.destroy()
    return ['success']

def method_create_object(environ):
    form    = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
    name = form.getvalue('obj_name')
    if not w.checkName(name): 
        if not name: name = ''
        log.debug('method_get_object_events: incorrect name %s', name)
        return ['object ' + name + ' not found']
    if len(name) < 4: return ['obj name should be larger']

    obj     = MSObject.MSObject(MSConfig.config.get('main','dbpath'), name)
    obj.open()
    if obj.storage.txn > 0: return ['object already exists']

    obj.storage.meta['msId']    = form.getvalue('obj_msId')
    obj.storage.meta['pcnId']   = form.getvalue('obj_pcnId')
    obj.storage.meta['skey']    = form.getvalue('obj_skey')
    obj.flush()
    return ['success'] 

def method_get_object_events(environ):
    form        = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)

    if form.getvalue('obj_tail'):
        tail = True
    else:
        tail = False

    if form.getvalue('obj_useapi'):
        useAPI = True
    else:
        useAPI = False

    if form.getvalue('obj_usedb'):
        useDB  = True
    else:
        useDB  = False

    reader = None
    if useAPI:
        reader = ReaderMSAPI.Reader(MSConfig.config.get('msapi','url'))
    if useDB:
        reader = ReaderMSDB.Reader(MSConfig.config.get('msdb','host'),
                                   MSConfig.config.get('msdb','port'),
                                   MSConfig.config.get('msdb','dbname'),
                                   MSConfig.config.get('msdb','user'),
                                   MSConfig.config.get('msdb','pwd'))

    startdate   = form.getvalue('obj_startdate')
    if startdate == None:
        startdate = MSDatetime.getToday()[0]
    else:
        startdate = datetime.datetime.strptime(startdate, MSDatetime.TIME_FORMAT_MAGICDB_ORIG)

    name        = form.getvalue('obj_name')
    if not w.checkName(name): 
        if not name: name = ''
        log.debug('method_get_object_events: incorrect name %s', name)
        return ['object ' + name + ' not found']
    obj  = MSDatabase.getInstance().objs.find(name)
    if reader != None:
        obj  = MSObject.MSObject(MSConfig.config.get('main', 'dbpath'), name)
        obj.open()
        if obj.storage.txn == 0:
            log.debug('method_get_object_events: not found %s', name)
            return ['object ' + name + ' not found']
        obj.lock.acquire()
        try:
            reader.getEvents_TIMED(obj, startdate)
        finally:
            obj.lock.release()

    ret = []
    ret += ['<h3>']
    ret += ['object "' + str(obj.objId) + '" since ' + startdate.strftime(MSDatetime.TIME_FORMAT_MAGICDB_ORIG)]
    ret += ['</h3><br/>']

    if tail:
        ret += w.openObjectEventTable(False)
    else:
        ret += w.openObjectEventTable(True)

    copied_events = list(obj.events)
    copied_events.reverse()
    for e in copied_events:
        ret += w.getObjectEventCommonInfo(e)
    ret += w.closeObjectEventTable()

    ret += ['<div class="eventTableSize">%d</div>' % len(obj.events)]
    ret += ['events processed totally at:']
    ret += ['<div class="eventTableUpdTime">' + (datetime.datetime.fromtimestamp(time.time())).strftime(MSDatetime.TIME_FORMAT_MAGICDB_ORIG) + '</div><br>']
    if tail:
        ret += ['<div class="eventTableObjName" hidden="true">' + name + '</div>']
        ret += ['<div class="eventTablePlaceholder" hidden="true"></div>']
        ret += ['<div class="eventTableAutoUpdate" hidden="true">true</div>']
        ret += ['<a class="maya2" href="blank">Enable RealTime Monitoring</a><br>']
    if useAPI:
        ret += ['<div class="eventTableMethod" hidden="true">api</div>']
    elif useDB:
        ret += ['<div class="eventTableMethod" hidden="true">db</div>']
    else:
        ret += ['<div class="eventTableMethod" hidden="true"></div>']
    return ret
'''

def handle_method(environ, start_response):
    w.putHeader(start_response, 200, 'html')
    mname = wsgiref.util.shift_path_info(environ)
    if mname == 'msysreceiver':
        return method_msysreceiver(environ)
    if mname == 'msysreceiver_com':
        return method_msysreceiver_com(environ)
    if mname == 'naviguardreceiver':
        return method_naviguardreceiver(environ)
    if mname == 'eldosreceiver':
        return method_eldosreceiver(environ)
    if mname == 'msysreceiver_start':
        return method_msysreceiver_start(environ)
    if mname == 'msysreceiver_stop':
        return method_msysreceiver_stop(environ)
    if mname == 'msysreceiver_configure':
        return method_msysreceiver_configure(environ)
    if mname == 'get_logs':
        return method_get_logs(environ)
    if mname == 'get_monitor':
        return method_get_monitor(environ)
    return ['not_found']
